<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>websocket demo</title>
</head>
<script>
    let socket;
    //判断当前浏览器是否支持websocket
    if (!window.WebSocket){
        alert("当前浏览器不支持websocket")
    }
    socket = new WebSocket("ws://localhost:7000/hello");
    //相当于channelRead0，ev 收到服务端会送的消息
    socket.onmessage = function (ev) {
        let rt = document.getElementById('responseText');
        rt.value = rt.value +"\n"+ev.data;
    }
    //相当于连接开启
    socket.onopen = function (ev){
        let rt = document.getElementById('responseText');
        rt.value = "连接开启了...";
    }
    //连接关闭（感知到连接关闭）
    socket.onclose = function (ev){
        let rt = document.getElementById('responseText');
        rt.value = rt.value +"\n"+"连接关闭";
    }
    //发送消息到服务器
    function send(message){
        console.log("send调用",message)
        if (socket.readyState == WebSocket.OPEN){
            console.log("发送消息")
            //通过socket发送消息
            socket.send(message);
        }else {
            alert("连接没有开启")
        }
    }
</script>
<body>
<form onsubmit="return false">
    <textarea name="message" style="height: 300px; width: 300px;"></textarea>
    <input type="button" value="发送消息" onclick="send(this.form.message.value)">
    <textarea id="responseText" style="height: 300px;width: 300px"></textarea>
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value = ''">
</form>
</body>
</html>